package com.gis.interceptors;

import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.gis.result.ResponseResult;
import com.gis.utils.JWTUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println(request);
        String token = request.getHeader("Authentication");
        System.out.println("Authentication" + token);
        try {
            Map<String, Object> claims = JWTUtils.parseToken(token);
            System.out.println(claims);
            return true;
        } catch (Exception e) {
            // System.out.println(e);
            System.err.println(e);
            response.setStatus(401);
            response.getWriter().println(ResponseResult.fail("Authentication FAIL"));
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
    
}
